package com.doudou.oauth.config.sms;

import com.doudou.oauth.filter.SmsCodeAuthenticationFilter;
import com.doudou.oauth.handler.FailLoginHandler;
import com.doudou.oauth.handler.SuccessLoginHandler;
import com.doudou.oauth.provider.SmsCodeAuthenticationProvider;
import com.doudou.oauth.service.MyUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author: 傻男人
 * @Date: 2020/5/22 10:42
 * @Version: 1.0
 * @Description: 短信验证码认证配置
 */
@Slf4j
@Configuration
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private SuccessLoginHandler successLoginHandler;

    @Autowired
    private FailLoginHandler failLoginHandler;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(failLoginHandler);
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(successLoginHandler);
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(myUserDetailsService);

        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
